package com.mengtian_tech.smart_farm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonView;
import com.mengtian_tech.smart_farm.model.PlantInfo;
import com.mengtian_tech.smart_farm.service.SystemService;
import com.mengtian_tech.smart_farm.vo.AjaxJson;
import com.mengtian_tech.smart_farm.vo.JsonViews;
import com.mengtian_tech.smart_farm.vo.Query;
/**
 * 种植库信息控制器
 */
@Controller
@RequestMapping("scgl/plant")
public class PlantInfoController {

	@Autowired
	SystemService systemService;
	
	@JsonView(JsonViews.PlantTreeView.class)
	@RequestMapping("list")
	@ResponseBody
	public AjaxJson list(@RequestBody(required = false) PlantInfo companyInfo) {
		
		if(companyInfo == null) companyInfo = new PlantInfo();
		Query<PlantInfo> q = Query.create(companyInfo);
		q.isNull("parent");
		List<PlantInfo> nodeList =  this.systemService.findList(q);		
		
		for(PlantInfo node :nodeList) {
			fetchChildren(node);
		}
		
		AjaxJson json = AjaxJson.getOk(nodeList);
		return json;
	}
	
	private void fetchChildren(PlantInfo parent) {
		Query<PlantInfo>  q = Query.create(PlantInfo.class);
		q.eq("parent.id", parent.getId());
		List<PlantInfo> children =  this.systemService.findList(q);
		
		if(children.size() > 0) {
			parent.setChildren(children);
			for(PlantInfo child: children) {
				fetchChildren(child);
			}
		}
		
	}
	
	/**
	 * 保存
	 * @param companyInfo
	 */
	@RequestMapping("save")
	@ResponseBody
	public AjaxJson save(@RequestBody PlantInfo companyInfo) {
		
		this.systemService.save(companyInfo);
		AjaxJson json = AjaxJson.getOk("保存成功");
		return json;
	}
	
	
	/**
	 * 删除
	 */
	@RequestMapping("delete")
	@ResponseBody
	public AjaxJson delete(@RequestBody PlantInfo companyInfo) {
		this.systemService.delete(companyInfo);
		AjaxJson json = AjaxJson.getOk("保存成功");
		return json;
	}
	
	
}
